package com.kaesar.leetcode.LeetCode_201_250;

import com.kaesar.leetcode.TreeNode;

public class LeetCode_235 {
    /**
     * 递归法
     *
     * @param root
     * @param p
     * @param q
     * @return
     */
    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // 如果p或q是根节点，直接返回根节点
        if (p == root) {
            return p;
        }
        if (q == root) {
            return q;
        }
        if (p.val < root.val && q.val < root.val) {
            // 如果p和q的值都小于root的值，则递归调用该方法，入参为 root.left
            return lowestCommonAncestor(root.left, p, q);
        } else if (p.val > root.val && q.val > root.val) {
            // 如果p和q的值都大于root的值，则递归调用该方法，入参为 root.right
            return lowestCommonAncestor(root.right, p, q);
        } else {
            // 如果p和q一个大于root的值，另一个小于root的值，则p和q的最近公共祖先只可能是root，所以直接返回root
            return root;
        }
    }

    public static void main(String[] args) {
        // 初始化一颗二叉搜索树
        TreeNode root = new TreeNode(6);
        TreeNode node_2 = new TreeNode(2);
        TreeNode node_8 = new TreeNode(8);
        root.left = node_2;
        root.right = node_8;
        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(4);
        root.left.right.left = new TreeNode(3);
        root.left.right.right = new TreeNode(5);
        root.right.left = new TreeNode(7);
        root.right.right = new TreeNode(9);

        // 调用方法，返回结果
        TreeNode result = lowestCommonAncestor(root, node_2, node_8);
        System.out.println(result.val);
    }
}
